package com.eascs.web.o2o.web.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eascs.app.dao.PageResult;
import com.eascs.app.exception.ControllerException;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.view.ViewContext;
import com.eascs.tag.MenuTag;
import com.eascs.web.o2o.web.common.BaseMasterViewController;
import com.eascs.web.o2o.web.entity.O2oPlatformRegional;
import com.eascs.web.o2o.web.form.OverdualForm;
import com.eascs.web.o2o.web.form.OverdualStatForm;
import com.eascs.web.o2o.web.form.ReportStatForm;
import com.eascs.web.o2o.web.service.BuildExcelService;
import com.eascs.web.o2o.web.service.OverdualReportService;
import com.eascs.web.o2o.web.service.ProvinceNameData;
import com.eascs.web.o2o.web.util.BankRowWriteHandler;

@Controller
@RequestMapping("/overdual")
public class OverdualReportController extends BaseMasterViewController {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	OverdualReportService overdualReportService;
	
	@Autowired
	ProvinceNameData provinceNameData;

	@Override
	public void preHandle() {
		super.preHandle();
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "report");
	}

	//
	@RequestMapping(value = "/overdualReport")
	public String overdualReport(OverdualForm vo) {
		String o2ourl = "/overdualRest/report";
		String reporto2ourl = "/overdual/download";
		if (vo != null) {

			o2ourl = UrlUtil.appendUrl(o2ourl, "billCode", vo.getBillCode());
			o2ourl = UrlUtil.appendUrl(o2ourl, "refundBank", vo.getRefundBank());
			o2ourl = UrlUtil.appendUrl(o2ourl, "status", vo.getStatus());
			o2ourl = UrlUtil.appendUrl(o2ourl, "province", vo.getProvince());
			o2ourl = UrlUtil.appendUrl(o2ourl, "loanName", vo.getLoanName());
			o2ourl = UrlUtil.appendUrl(o2ourl, "ltd", vo.getLtd());
			o2ourl = o2ourl + "&pageIndex=";
		} else {
			o2ourl = o2ourl + "?pageIndex=";
		}

		ViewContext.put("oaurl", o2ourl);
		ViewContext.put("reporto2ourl", reporto2ourl);
		ViewContext.put("vo", vo);

		return "overdual/overdualList";
	}

	@RequestMapping("/download")
	public void dowanload(OverdualForm vo, HttpServletResponse httpServletResponse, HttpServletRequest request) {
		// BaseRestResult<String> result = null;
		vo.setPageSize(Integer.MAX_VALUE);
		vo.setType(1);
		PageResult<Object[]> pageResult = overdualReportService.getOverdualReportByPage(vo);

		saveAfterLoan(pageResult.getData());
		// String file =
		// O2oPaymentsRestController.class.getResource("/excelTemplate/AfterLoan.xls").getPath();
		// String file = excelExportAfterLoan;
		String path = OverdualReportController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/overdual_report.xls").toString();
		OutputStream os = null;
		try {
			String outfile = "贷后逾期数据.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
		// return result;
	}

	// 先生成文件然后在读这个文件
	public String saveAfterLoan(List<Object[]> data) {
		// 模板
		String soucreFileName = "/excelTemplate/overdual.xls";
		// 输出路径
		String path = OverdualReportController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/overdual_report.xls").toString();

		int col = 17;
		// 需要统计的列
		int[] arr = { 6, 10, 11, 12, 13, 14, 15 };
		String title = "贷后逾期数据";
		// 开始的表格，行，列
		int sheetIndex = 0;
		int rowIndex = 3;
		int columnIndex = 0;
		// 生产excel
		BankRowWriteHandler bankRowWriteHandler = new BankRowWriteHandler(data, col, arr, Arrays.asList(title),
				sheetIndex, rowIndex, columnIndex);

		// 生产excel
		write(soucreFileName, outPath, bankRowWriteHandler);

		// 存放的文件的文件夹
		return path + "/" + outPath;
	}

	// 根据平台查询逾期报表
	@RequestMapping(value = "/overdualReportByPlatform")
	public String overdualReportByPlatform(ReportStatForm entity) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "overdualReportByPlatform");
		String o2ourl = "/overdualRest/overdualPlatform";

		if (entity != null) {
			String province = entity.getProvince() == null ? "" : entity.getProvince();
			o2ourl = UrlUtil.appendUrl(o2ourl, "province", province);
			o2ourl = o2ourl + "&o2oIndex=";
		} else {
			o2ourl = o2ourl + "?o2oIndex=";
		}
		List<O2oPlatformRegional> proList = provinceNameData.getProvinceNameData();
		
		ViewContext.put("o2ourl", o2ourl);
		ViewContext.put("vo", entity);
		ViewContext.put("proList", proList);
		return "overdual/platformOverdualList";
	}

	// 平台查询报表逾期下载
	@RequestMapping("/downloadOverdualPlatform")
	public void downloadPlatform(OverdualStatForm entity, HttpServletResponse httpServletResponse,
			HttpServletRequest request) {
		String province = entity.getProvince();
		Date nowTime = new Date(System.currentTimeMillis());
		SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd");
		String today = sdFormatter.format(nowTime); // 今天时间
		entity.setPageSize(Integer.MAX_VALUE);
		PageResult<Object[]> pageResult = overdualReportService.getOverdualReportStatByPlatformByPage(entity);
		saveReportStatByPlatform(pageResult.getData(), province);
		String path = MonReportController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/overdualReportstat.xls").toString();
		OutputStream os = null;
		try {
			String outfile;
			if (province == null) {
				outfile = "O2O金融业务台账明细-按平台" + "（截止到：" + today + "）" + ".xls";
			} else {
				outfile = entity.getProvince() + "-O2O金融业务台账明细-按平台" + "（截止到：" + today + "）" + ".xls";
			}
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}

	public String saveReportStatByPlatform(List<Object[]> data, String province) {
		String pro = province;
		Date nowTime = new Date(System.currentTimeMillis());
		SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd");
		String today = sdFormatter.format(nowTime); // 今天时间
		// 模板
		String soucreFileName = "/excelTemplate/excel-pingtai-report.xls";
		// 输出路径
		String path = MonReportController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/overdualReportstat.xls").toString();

		// 包含的列
		int col = 14;
		// 需要统计的列
		int[] arr = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
		String title;
		if (pro == null) {
			title = "O2O金融业务台账明细-按平台" + "（截止到：" + today + "）";
		} else {
			title = pro + "-O2O金融业务台账明细-按平台" + "（截止到：" + today + "）";
		}

		// 开始的表格，行，列
		int sheetIndex = 0;
		int rowIndex = 3;
		int columnIndex = 0;
		BankRowWriteHandler bankRowWriteHandler = new BankRowWriteHandler(data, col, arr, Arrays.asList(title),
				sheetIndex, rowIndex, columnIndex);

		// 生产excel
		write(soucreFileName, outPath, bankRowWriteHandler);

		return path + "/" + outPath;
	}

	// 根据省区查询逾期报表
	@RequestMapping(value = "/overdualReportByProvince")
	public String overdualReportByProvince(ReportStatForm entity) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "overdualReportByProvince");
		String o2ourl = "/overdualRest/overdualProvince";

		if (entity != null) {
			String province = entity.getProvince() == null ? "" : entity.getProvince();
			o2ourl = UrlUtil.appendUrl(o2ourl, "province", province);
			o2ourl = o2ourl + "&o2oIndex=";
		} else {
			o2ourl = o2ourl + "?o2oIndex=";
		}
		List<O2oPlatformRegional> proList = provinceNameData.getProvinceNameData();
		
		ViewContext.put("o2ourl", o2ourl);
		ViewContext.put("vo", entity);
		ViewContext.put("proList", proList);
		return "overdual/provinceOverdualList";
	}

	// 省区查询报表逾期下载
	@RequestMapping("/downloadOverdualProvince")
	public void downloadProvince(OverdualStatForm entity, HttpServletResponse httpServletResponse,
			HttpServletRequest request) {
		String province = entity.getProvince();
		Date nowTime = new Date(System.currentTimeMillis());
		SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd");
		String today = sdFormatter.format(nowTime); // 今天时间
		entity.setPageSize(Integer.MAX_VALUE);
		PageResult<Object[]> pageResult = overdualReportService.getOverdualReportStatByProvinceByPage(entity);
		saveReportStatByProvince(pageResult.getData(), province);
		String path = MonReportController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/overdualReportstat.xls").toString();
		OutputStream os = null;
		try {
			String outfile;
			if (province == null) {
				outfile = "O2O金融业务台账明细-按省区" + "（截止到：" + today + "）" + ".xls";
			} else {
				outfile = entity.getProvince() + "-O2O金融业务台账明细-按省区" + "（截止到：" + today + "）" + ".xls";
			}
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}

	public String saveReportStatByProvince(List<Object[]> data, String province) {
		String pro = province;
		Date nowTime = new Date(System.currentTimeMillis());
		SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd");
		String today = sdFormatter.format(nowTime); // 今天时间
		// 模板
		String soucreFileName = "/excelTemplate/excel-sheng-report.xls";
		// 输出路径
		String path = MonReportController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/overdualReportstat.xls").toString();

		// 包含的列
		int col = 14;
		// 需要统计的列
		int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
		String title;
		if (pro == null) {
			title = "O2O金融业务台账明细-按省区" + "（截止到：" + today + "）";
		} else {
			title = pro + "-O2O金融业务台账明细-按省区" + "（截止到：" + today + "）";
		}

		// 开始的表格，行，列
		int sheetIndex = 0;
		int rowIndex = 3;
		int columnIndex = 0;
		BankRowWriteHandler bankRowWriteHandler = new BankRowWriteHandler(data, col, arr, Arrays.asList(title),
				sheetIndex, rowIndex, columnIndex);

		// 生产excel
		write(soucreFileName, outPath, bankRowWriteHandler);

		return path + "/" + outPath;
	}

	/*
	 * 生成excel 参数：数据，源文件，输出文件，excel包含的列，需要统计的列，excel标题
	 */
	public void write(String soucreFileName, String outPath, BankRowWriteHandler bankRowWriteHandler) {
		IoUtil.createDirectorieIfMissing(new File(outPath).getParentFile());
		try {
			ExcelApiHelper.writeHandle(new FileOutputStream(outPath),
					BuildExcelService.class.getResourceAsStream(soucreFileName), bankRowWriteHandler);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ControllerException(e);
		}
	}

}
